package com.huanglj.himalaya.activitys;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.Rect;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.huanglj.himalaya.R;
import com.huanglj.himalaya.adapters.DetailAdapter;
import com.huanglj.himalaya.base.BaseActivity;
import com.huanglj.himalaya.base.BaseApplication;
import com.huanglj.himalaya.interfaces.IAlbumDetailViewCallback;
import com.huanglj.himalaya.interfaces.IPlayerCallBack;
import com.huanglj.himalaya.interfaces.ISubscriptionCallback;
import com.huanglj.himalaya.presenters.AlbumDetailPresenter;
import com.huanglj.himalaya.presenters.PlayerPresenter;
import com.huanglj.himalaya.presenters.SubscriptionPresenter;
import com.huanglj.himalaya.utils.BlurTransformation;
import com.huanglj.himalaya.utils.LogUtil;
import com.huanglj.himalaya.views.UILoader;
import com.lcodecore.tkrefreshlayout.IBottomView;
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;
import com.lcodecore.tkrefreshlayout.header.bezierlayout.BezierLayout;
import com.ximalaya.ting.android.opensdk.model.album.Album;
import com.ximalaya.ting.android.opensdk.model.track.Track;
import com.ximalaya.ting.android.opensdk.player.service.XmPlayListControl;

import net.lucode.hackware.magicindicator.buildins.UIUtil;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.indicators.BezierPagerIndicator;

import java.util.List;

public class DetailActivity extends BaseActivity implements IAlbumDetailViewCallback, DetailAdapter.OnDetailOnclickListener, UILoader.OnRetryClickListener, IPlayerCallBack, View.OnClickListener, IBottomView, ISubscriptionCallback {

    private static final String TAG = "DetailActivity";
    private ImageView mLargeCover;
    private ImageView mSmallCover;
    private TextView mAlbumTitle;
    private TextView mAlbumAuthor;
    private Album mAlbum;
    private RecyclerView mDetailListView;
    private DetailAdapter mDetailAdapter;
    private UILoader mUiLoader;
    private FrameLayout mDetailItemList;
    private AlbumDetailPresenter mDetailPresenter;
    private long mId;
    private ImageView mDetailPlay;
    private PlayerPresenter mPlayerPresenter;
    private List<Track> mCurrentTracks;
    private TwinklingRefreshLayout mRefreshLayout;
    private BezierPagerIndicator mBezierPagerIndicator;
    private TextView mTextTitle;
    private Track mTrack;
    private int mSize;
    private View mButtonView;
    private View mSubBtn;
    private SubscriptionPresenter mSubscriptionPresenter;
    private TextView mSubText;


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_detail);
        //把状态栏设置成透明
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            //把状态栏隐藏掉
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION);
            getWindow().setStatusBarColor(Color.TRANSPARENT);
            //初始化控件
            initView();

            mDetailPresenter = AlbumDetailPresenter.getInstance();
            mDetailPresenter.registerViewCallBack(this);
            //获取数据
            mId = mAlbum.getId();
            mDetailPresenter.getAlbumDetail((int) mId,1);
            mPlayerPresenter = PlayerPresenter.getPlayerPresenter();
            mPlayerPresenter.registerViewCallBack(this);

            mSubscriptionPresenter = SubscriptionPresenter.getInstance();
            mSubscriptionPresenter.registerViewCallBack(this);
            updatePlaySate(mPlayerPresenter.isPlay());
            updateSubState();

        }
    }

    private void updateSubState() {
        if (mSubscriptionPresenter != null) {
            boolean isSub = mSubscriptionPresenter.isSub(mAlbum);
            mSubText.setText(isSub ? R.string.sub_cancel_text : R.string.sub_text);
        }
    }

    private void initEvent() {

        BezierLayout headerView = new BezierLayout(this);
        mRefreshLayout.setHeaderView(headerView);
        mRefreshLayout.setMaxHeadHeight(140);
        mRefreshLayout.setOverScrollBottomShow(false);
        mRefreshLayout.setBottomView(this);
        //上拉刷新，下拉加载更多
        mRefreshLayout.setOnRefreshListener(new RefreshListenerAdapter() {
            @Override
            public void onRefresh(TwinklingRefreshLayout refreshLayout) {
                BaseApplication.getHandler().postDelayed(new Runnable() {
                    //加载刷新事件
                    @Override
                    public void run() {

                        Toast.makeText(DetailActivity.this,"刷新",Toast.LENGTH_SHORT).show();
                        mRefreshLayout.finishRefreshing();
                    }
                },3000);

                super.onRefresh(refreshLayout);
            }

            @Override
            public void onLoadMore(TwinklingRefreshLayout refreshLayout) {
                super.onLoadMore(refreshLayout);
                mDetailPresenter.loadMore();
                isLoadMore = true;
//                BaseApplication.getHandler().postDelayed(new Runnable() {
//                    @Override
//                    public void run() {
//                        Toast.makeText(DetailActivity.this,"加载",Toast.LENGTH_SHORT).show();
//
//                    }
//                },3000);


            }
        });

    }

    private void updatePlaySate(boolean isPlay) {
        if (mDetailPlay != null) {
            mDetailPlay.setImageResource(isPlay ? R.mipmap.pause_black_normal : R.mipmap.play_black_normal);
        }
    }

    private View createSuccessView() {
        View inflate = LayoutInflater.from(this).inflate(R.layout.item_recycler_view, null, false);
        mRefreshLayout = inflate.findViewById(R.id.refreshLayout);
        mButtonView = LayoutInflater.from(mRefreshLayout.getContext()).inflate(R.layout.button_view, mRefreshLayout, false);
        mDetailListView = inflate.findViewById(R.id.success_item);
        mBezierPagerIndicator = new BezierPagerIndicator(this);
        initEvent();
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        mDetailListView.setLayoutManager(linearLayoutManager);
        mDetailAdapter = new DetailAdapter();
        mDetailListView.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
                outRect.bottom= UIUtil.dip2px(view.getContext(),4);

            }
        });
        mDetailAdapter.setOnDetailOnclickListener(this);
        mDetailListView.setAdapter(mDetailAdapter);

        return inflate;
    }

    private void initView() {
        mDetailItemList = findViewById(R.id.track_item_view);
        if (mUiLoader == null) {
            mUiLoader = new UILoader(this) {
                @Override
                protected View getSuccessView() {
                    return createSuccessView();
                }
            };
        }
        //网络不好时，刷新
        mUiLoader.setOnRetryClickListener(this);
        mDetailItemList.removeAllViews();
        mDetailItemList.addView(mUiLoader);
        mLargeCover = findViewById(R.id.iv_large_cover);
        mSmallCover = findViewById(R.id.iv_small_cover);
        mAlbumTitle = findViewById(R.id.tv_album_title);
        mAlbumAuthor = findViewById(R.id.tv_album_author);
        mDetailPlay = findViewById(R.id.detail_item_play);
        mDetailPlay.setOnClickListener(this);
        mTextTitle = findViewById(R.id.play_detail_title);
        mSubBtn = findViewById(R.id.detail_sub_btn);
        mSubBtn.setOnClickListener(this);
        mSubText = findViewById(R.id.detail_sub_text);
    }

    private boolean isLoadMore = false;
    @Override
    public void onDetailListLoaded(List<Track> tracks) {
        if (isLoadMore == true && mRefreshLayout != null){
            mRefreshLayout.finishLoadmore();
        }
        this.mCurrentTracks = tracks;
        mDetailAdapter.setData(tracks);
        if(tracks.size()!= 0){
            mUiLoader.updateStatus(UILoader.UIStatus.SUCCESS);
        }else {
            mUiLoader.updateStatus(UILoader.UIStatus.EMPTY);
        }

    }

    @Override
    public void onNetworkError() {
        mUiLoader.updateStatus(UILoader.UIStatus.NETWORK_ERROR);
    }

    @Override
    public void onEmpty() {
        mUiLoader.updateStatus(UILoader.UIStatus.EMPTY);
    }

    @Override
    public void onLoading() {
        mUiLoader.updateStatus(UILoader.UIStatus.LOADING);
    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
    @Override
    public void onAlbumLoader(Album album) {
        mAlbum = album;

        //加载控件信息
        //不用这种
//        Picasso.with(this).load(album.getCoverUrlLarge()).into(mLargeCover, new Callback() {
//            //成功后加载高斯效果
//            @Override
//            public void onSuccess() {
//                ImageBlur.makeBlur(mLargeCover,DetailActivity.this);
//            }
//
//            @Override
//            public void onError() {
//
//            }
//        });
        Glide.with(this).load(album.getCoverUrlLarge()).apply(RequestOptions.bitmapTransform(new BlurTransformation(DetailActivity.this,20,3))).into(mLargeCover);
        Glide.with(this).load(album.getCoverUrlLarge()).into(mSmallCover);

        mAlbumTitle.setText(album.getAlbumTitle());
        mAlbumAuthor.setText(album.getAnnouncer().getNickname());
    }

    @Override
    public void loadFinish(int size) {
        if(size == 0){
            TextView buttonText = mButtonView.findViewById(R.id.button_text);
            buttonText.setText("已经没有更多了");
            getView();
        }
    }

    /**
     * 点击是跳转进界面
     * @param trackList
     * @param position
     */
    @Override
    public void onItemClick(List<Track> trackList, int position) {
        mPlayerPresenter.setPlayList(trackList,position);
        Intent intent = new Intent(this, PlayerActivity.class);
        startActivity(intent);
    }

    /**
     * 销毁时，取消绑定
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(mDetailPresenter != null){
            mDetailPresenter.unRegisterViewCallBack(this);
            mPlayerPresenter.unRegisterViewCallBack(this);
        }
    }

    /**
     * 这里重新获取数据
     */
    @Override
    public void onRetryClick() {
        mDetailPresenter.getAlbumDetail((int) mId,1);
    }

    @Override
    public void onPlayStart() {
        mDetailPlay.setImageResource(R.mipmap.pause_black_normal);
        Log.d(TAG, "onPlayStart: " + mDetailPlay);
        updatePlaySate(true);
        mTextTitle.setText(mTrack.getTrackTitle());
    }

    @Override
    public void onPlayPause() {
        updatePlaySate(false);
        mTextTitle.setText(R.string.click_on_play);
    }

    @Override
    public void onPlayStop() {
        updatePlaySate(false);
        mTextTitle.setText(R.string.click_on_play);
    }

    @Override
    public void onPlayError() {

    }

    @Override
    public void onNextPlay(Track track) {

    }

    @Override
    public void onPrePlay(Track track) {

    }

    @Override
    public void onListLoaded(List<Track> list) {

    }

    @Override
    public void onPlayModeChange(XmPlayListControl.PlayMode mode) {

    }

    @Override
    public void onProgressChange(int currentProgress, int total) {

    }

    @Override
    public void onAdLoading() {

    }

    @Override
    public void onAdFinished() {

    }

    @Override
    public void onTrackUpdate(Track track, int playIndex) {
        if (track != null) {
            mTrack = track;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.detail_item_play:
                //判断播放器是否有播放列表
                //TODO:
                boolean hasList = mPlayerPresenter.hasPlayList();
                if(hasList){
                    LogUtil.d(TAG,"onClick");
                    if(mPlayerPresenter.isPlay()){
                        mPlayerPresenter.pause();
                    }else {
                        mPlayerPresenter.play();
                    }
                    break;
                }else {
                    mPlayerPresenter.setPlayList(mCurrentTracks,0);
                }
                break;
            case R.id.detail_sub_btn:
                boolean isSub = mSubscriptionPresenter.isSub(mAlbum);
                if (isSub) {
                    mSubscriptionPresenter.deleteSubscription(mAlbum);
                }else {
                    mSubscriptionPresenter.addSubscription(mAlbum);
                }
                break;
        }
    }
    //------------------ button view 的接口----------------------------------
    @Override
    public View getView() {
        return mButtonView;
    }

    @Override
    public void onPullingUp(float fraction, float maxBottomHeight, float bottomHeight) {

    }

    @Override
    public void startAnim(float maxBottomHeight, float bottomHeight) {

    }

    @Override
    public void onPullReleasing(float fraction, float maxBottomHeight, float bottomHeight) {

    }

    @Override
    public void onFinish() {

    }

    @Override
    public void reset() {

    }

    @Override
    public void onAddResult(boolean success) {
        Toast toast = Toast.makeText(this, "", Toast.LENGTH_SHORT);
        if (success) {
            mSubText.setText(R.string.sub_cancel_text);
            toast.setText("订阅成功");
        }else {
            toast.setText("订阅失败");
        }
        toast.show();
    }

    @Override
    public void onDeleteResult(boolean success) {
        Toast toast = Toast.makeText(this, "", Toast.LENGTH_SHORT);
        if (success) {
            mSubText.setText(R.string.sub_text);
            toast.setText("取消订阅成功");
        }else {
            toast.setText("订阅失败");
        }
        toast.show();
    }

    @Override
    public void onGetListLoad(List<Album> result) {

    }
}
